// 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}
let one = new ListNode(1);
let two = new ListNode(2);
let thr = new ListNode(3);
let four = new ListNode(4);
one.next = two;
two.next = thr;
thr.next = four;
var rotateRight = function(head, k) {
    let len = 0;
    let len2 = 0;
    let res = head;
    let res2 = head;
    if (head == null || head.next == null) { return head }
    if (k < 2) { return head }
    while (res2.next != null) {
        len2++;
        res2 = res2.next;
    }
    len2++;
    k = k % len2;
    while (len != k) {
        len++;
        res = res.next
    }
    let temp = res.next;
    res.next = null;
    let tem = temp
    while (tem.next != null) {
        tem = tem.next
    }
    tem.next = head;
    return temp
}
var rotateRight = function(head, k) {
    if (k === 0 || !head || !head.next) {
        return head; //除去边界条件
    }
    let n = 1;
    let cur = head;
    // 先遍历出链表的长度
    while (cur.next) {
        cur = cur.next;
        n++;
    }

    let add = n - k % n; //注意环形链表
    // 移动整数倍直接返回头节点
    if (add === n) {
        return head;
    }
    //    使链表称为一个环形链表
    cur.next = head;
    //将节点后移
    while (add) {
        cur = cur.next;
        add--;
    }
    const ret = cur.next;
    // 利用cur.next=null将环形链表分割
    cur.next = null;
    return ret;
};
rotateRight(one, 2)
console.log(one)